package com.controller.infocenter;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException;
import com.po.InformationInfo;
import com.service.infocenter.UserService;
import com.service.information.InformationService;
import com.util.ImportExcelUtil;
import com.util.Office2PDF;
import com.util.StringFinal;

@Controller
@RequestMapping("/jsp/infocenter")
public class FileUploadController {
 
	@Resource(name="userServiceImp")
	private UserService userService;
	@Resource(name="informationServiceImp")
	private InformationService informationService;
	/**
	 * 返回未审核的页面
	 * @return
	 */
	@RequestMapping(value="/getMultifileview")
	public String getMultifileview(){
		
		return "infocenter/multifileupload";
	}
	/**
	 * 修改个人头像
	 * @param file
	 * @param request
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value="/uploadImage")
	public Object getImage(@RequestParam("image") MultipartFile file,HttpServletRequest request) {
		
		int result = 0;
		String userid = request.getSession().getAttribute("user_id").toString();
		String filename = file.getOriginalFilename();
		String[] types= filename.split("\\.");
		String type=types[types.length-1];
		String imagepath = request.getSession().getServletContext().getRealPath("/image/user/"+userid+"."+type);
		File file1 = new File(imagepath);
		StringBuffer buffer = new StringBuffer();
		buffer.append(userid).append(".").append(type);
		//Map<String, Integer> map = new HashMap<String, Integer>();
		try {
			file.transferTo(file1);
			result = userService.updateUserImage(buffer.toString(), userid);
		} 
		 catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result = 0;
		}			
		//map.put("result", result);
		return result;
	}
	
	/**
	 *多个文件上传,批量上传
	 * @param request
	 * @param test
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/multiupload")
	public String Mutiuploadfilen(@RequestParam("excelinput")MultipartFile file,@RequestParam("filesinput")MultipartFile[] files,HttpServletRequest request,String kudata){
		
		StringBuffer result = new StringBuffer();
		String userid = request.getSession().getAttribute("user_id").toString();
		int count = 0;
		int size = 0;
		int repcount = 0;
		StringBuffer namebuffer = new StringBuffer();
		StringBuffer repeatid = new StringBuffer();
		StringBuffer viewstring = new StringBuffer();
		int viewcount = 0;
		try {
			InputStream in = file.getInputStream();
			ImportExcelUtil imexcel = new ImportExcelUtil();
			String filename = file.getOriginalFilename();
			Map<String,InformationInfo> mapinfo =  imexcel.getBankMapByExcel(in, filename, userid, kudata);
			 size = mapinfo.size();
			if(size==files.length){
					StringBuffer buffer = new StringBuffer();
					String fname;
					String filepath;
					File filedata;
					String viewname;
					String viewpath;
					File viewfile;
					StringBuffer viewbuffer = new StringBuffer();
					DocumentConverter converter =  Office2PDF.startService();
					for(MultipartFile f:files){
						 fname = f.getOriginalFilename();
						 if( mapinfo.get(fname) != null){
							 InformationInfo info =  mapinfo.get(fname);
							 if(informationService.getInformation(info) !=0)
							 {
								 repcount++;
								 repeatid.append(info.getExcelid()+";");
								 continue;
							 }
							 fname = buffer.append(info.getInfo_id()).append("_").append(fname).toString();
							 filepath = request.getServletContext().getRealPath(StringFinal.path+fname);
							 filedata = new File(filepath);
							 f.transferTo(filedata);
							 informationService.addUploadinfo(info);
							 buffer.setLength(0);
							 //用于文件预览,生成pdf文件
							 String[] pf = fname.split("\\."); 
							 if(pf[1].contains("doc")||pf[1].contains("ppt")||pf[1].contains("xls")){
								 viewname = viewbuffer.append(pf[0]).append(StringFinal.postfix).toString();
								 viewpath = request.getServletContext().getRealPath("/"+StringFinal.viewpath+viewname);
								 viewfile = new File(viewpath);
								 try{
									 converter.convert(filedata, viewfile);
								    }
								 catch(OpenOfficeException e){
									 viewstring.append(info.getExcelid()+";");
									 viewcount++;
								 }
							 }
							 viewbuffer.setLength(0);
							 count++;
						 }
						 else
						 {
							 namebuffer.append(fname+";");
							 
						 }
					
					}
			}
			else{
				count=0;
				return count+",tag";//个数不相等
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			return "tag";//一般是excel模板不符合要求，或者缺少必填项
		}
		finally 
		{
			Office2PDF.stopService();

		}
		//没有失败的
		if(namebuffer.toString()==null||namebuffer.toString().equals(""))
			result.append(count+","+(size-count-repcount)+","+repcount+","+repeatid.toString()+","+viewcount+","+viewstring.toString());
		else//有失败的
			result.append(count+","+(size-count-repcount)+","+repcount+","+namebuffer.toString()+","+repeatid.toString()+","+viewcount+","+viewstring.toString());
		
		return result.toString();
	}
}
